var canvs = document.getElementById("chess");
var ctx = canvs.getContext("2d");

/**
 * 画棋盘
 */
function drawPan(ctx) {
    ctx.strokeStyle = "#888";
    for (var i = 0; i < 15; i++) {
        var y = 15 + 30 * i, x1 = 15, x2 = 435;
        ctx.moveTo(x1, y);
        ctx.lineTo(x2, y);
        ctx.stroke();
        ctx.beginPath();
        ctx.textBaseline='middle';
        ctx.fillText(i,0,y);
        ctx.closePath();
    }
    for (var i = 0; i < 15; i++) {
        var y = 15 + 30 * i, x1 = 15, x2 = 435;
        ctx.moveTo(y, x1);
        ctx.lineTo(y, x2);
        ctx.stroke();
        ctx.beginPath();
        ctx.textAlign='center';
        ctx.fillText(i,y,5);
        ctx.closePath();
    }
}
drawPan(ctx);

/**
 * 画棋子
 * @param x
 * @param y
 * @param white
 */
function drawZi(x,y,white,red) {


    ctx.beginPath();
    ctx.arc(x, y, 12, 0, 2 * Math.PI);
    ctx.closePath();
    var cgt = ctx.createRadialGradient(x,y,12,x,y,0);
     if(red){
         if(white){
              cgt.addColorStop(0,'#333');
         }else{
              cgt.addColorStop(0,'#aaa');
         }
        // cgt.addColorStop(0,'#f00');
        cgt.addColorStop(1,'#ff0');
    }else if(!white){
        cgt.addColorStop(0,'#333');
        cgt.addColorStop(1,'#ccc');
    }else{
        cgt.addColorStop(0,'#aaa');
        cgt.addColorStop(1,'#fff');
    }


    ctx.fillStyle=cgt;
    ctx.fill();
}
function luozi2(x,y,white) {

}

var G={
    black : false
};




(function (w, g) {
    var points = [];
    points.getPoint=function(x,y){
        if(x<0||x>=15)return null;
        if(y<0||y>=15)return null;
        return points[x][y];
    }
    var fangAns = [];
    var pointSingle=[];

    function point(x,y) {
        this.x=x;
        this.y=y;
        this.color=-1;//黑1，白2
        this.fangAns=[];
        this.score = 0;//评分
    }
    w.point=point;
    var handler = [function (x, y,fangan) {//竖
        fangan.start=points.getPoint(x,y-1);
        fangan.end=points.getPoint(x,y+5);
    },function (x, y, fangan) {//横
        fangan.start=points.getPoint(x-1,y);
        fangan.end=points.getPoint(x+5,y);
    },function (x, y, fangan) {//斜
        fangan.start=points.getPoint(x-1,y-1);
        fangan.end=points.getPoint(x+5,y+5);
    },function (x, y, fangan) {//反斜
        fangan.start=points.getPoint(x+1,y-1);
        fangan.end=points.getPoint(x-5,y+5);
    }];

    window.scoreType = [
        300000,//4子
        40000,//3子无遮
        5000,//2子无遮
        100,//有效方案数
        100,//每个step
        2000,//内部子

    ];
    function fangAn(type,x,y) {
        this.points=[];
        this.step=0;//已经完成的点
        this.color=0;//对那方有效,0:all,1:black;2:white,-1:allnot
        this.type = type;
        handler[type - 1](x, y, this);
        this.add=function (x, y) {
            var point = points[x][y];
            this.points.push(point);
            point.fangAns.push(this);
        };
        this.isCompute=function () {
            return this.color==1;
        };
        this.over=function () {
            return this.step>=5;
        };

        this.addScore=function (st) {
            this.start && (this.start.score+=scoreType[st]);
            this.end && (this.end.score+=scoreType[st]);
            this.points.forEach(item=>{
                if(item.color==-1){
                    item.score+=scoreType[st]+scoreType[5];
                }
            })
        }
    }
    var ii=0;
    for(var i=0;i<15;i++){
        points[i]=[];
        for(var j=0;j<15;j++){
            var tt = new point(i,j);
            points[i][j]=tt;
            pointSingle[ii++]=tt;
        }
    }


    var fa = null,fa1=null;

    //1:竖,2:横线3:斜线4:反斜线
    for(var i =0;i<15;i++){//x
        for(var j=0;j<11;j++){//y
            fa = new fangAn(1,i,j),//列
                fa1=new fangAn(2,j,i);//行
            for (var k=0;k<5;k++){
                fa.add(i,j+k); //添加列
                fa1.add(j+k,i);//添加行
            }
            fangAns.push(fa);
            fangAns.push(fa1);
        }
    }

    for(var i =0;i<11;i++){//x
        for(var j=0;j<11;j++){//y
            fa = new fangAn(3,i,j);
            for (var k=0;k<5;k++){
                fa.add(i+k,j+k); //添加列
            }
            fangAns.push(fa);
        }
    }
    for(var i =14;i>3;i--){//x
        for(var j=0;j<11;j++){//y
            fa = new fangAn(4,i,j);
            for (var k=0;k<5;k++){
                fa.add(i-k,j+k); //添加列
            }
            fangAns.push(fa);
        }
    }

    G.points=points;
    G.fangAns=fangAns;
    G.pointSingle=pointSingle;
})(window,G);

var handler = {
    nomal:function(e){
        var a=Math.floor(e.layerX/30),b=Math.floor(e.layerY/30);
         var x= a*30+15,
            y=b*30+15;
        //TODO 判断改点是否有子存在
        if(G.points[a][b].color!=-1){
            emit('exsis-zi',a,b);
            return;
        }
        drawZi(x,y,(G.black=!G.black));
        emit('luo-zi',a,b,!G.black);
        canvs.onclick=handler.conpute;
        emit('place-start-play')
    },
    over:function (e) {
        alert("棋局已结束")
    },
    conpute:function () {
        alert("电脑也要思考")
    }
};

canvs.onclick=handler.nomal;


on('luo-zi',function (x,y,black) {
    if(G.fangAns.length==1){
        alert("和其正");
        emit('game-over', null,null);
        return;
    }
    try {
        var color = black ? 1 : 2;
        G.points[x][y].color = color;
        G.points[x][y].fangAns.forEach(function (item) {
            if (item.color == -1) {//无效方案,双方都有落子
                return;
            }
            if (item.color == 0) {//双方都有效都方案
                item.color = color;
            }
            if (item.color == color) {//对己方有效对方案
                item.step++;
            } else {
                item.color = -1;
                item.step = 0;
            }
            if (item.over()) {
                emit('game-over', black,item);
                var error = new Error("游戏结束");
                throw error;
            }

        });
    } catch (e) {
    }
});

var sikao=[
    function (fangan) {//四子连珠
        if(fangan.step==4){
            if(fangan.isCompute())
                throw fangan.points.filter(item=>item.color==-1);
            else{
                fangan.addScore(0);
            }
        }
    },
    function (fangan) {//三子无遮掩
        var temp=fangan.step==3
            &&  (fangan.start && fangan.start.color==-1
            ||  fangan.end && fangan.end.color==-1);
        if(temp){
            fangan.addScore(1);
        }
    },
    function (fangan) {//TODO 二子无遮掩
        var temp=fangan.step==2
            &&  fangan.start && fangan.start.color==-1
            &&  fangan.end && fangan.end.color==-1;
        if(temp){
            fangan.addScore(2);
        }
    },
    function (fangan) {//每点可连接方案数量
        fangan.points.forEach(function (item) {

            var score=item.fangAns.map(function (fa) {
                // 如果这个点的有效方案
                // 方案的step
                if(fa.color==-1)return 0;
                var result =  scoreType[3]+scoreType[4]*fa.step;
                if(fa.step==3){
                    result+=scoreType[4]*20;
                }
                return result;
            }).reduce(function (a, b) {
                return a+b;
            });
            item.score+=score;
        });
    }

];

on('exsis-zi',function (x,y,black) {
     alert(`${x}:${y}点已经柚子了`);
});
 on('game-over',black=>{
     alert("游戏结束"+(black?"hei":"bai")+"方获胜");
     handler.nomal=handler.over;
     canvs.onclick=handler.over;
     console.log(canvs.onclick);
 });
on('place-start-play',function () {
    G.fangAns=G.fangAns.filter(item=>item.color!=-1);
    G.pointSingle.forEach(function(item){
        item.score=0;
    });
    try {
        G.fangAns.forEach(item=> {
            sikao.forEach(func=>func(item));
        });
    } catch (e) {
        if(e[0] instanceof point){
            emit('comput-luo-zi',e[0]);
         canvs.onclick=handler.nomal;
        }else{
            console.error(e);
        }

        return;
    }
    G.pointSingle = G.pointSingle.filter(item=>item.color==-1);
    G.pointSingle.sort(function (a, b) {
        return b.score-a.score;
    });
    emit('comput-luo-zi',G.pointSingle[0]);
    canvs.onclick=handler.nomal;
    console.log("over");
});

on('comput-luo-zi',function (a) {
     var x= a.x*30+15,
            y=a.y*30+15;
        drawZi(x,y,(G.black=!G.black));
        emit('luo-zi',a.x,a.y,!G.black);
        canvs.onclick=handler.nomal;
});
on('game-over', (black,item)=>{
    item.points.forEach(a=>{
         var x= a.x*30+15,
            y=a.y*30+15;
        drawZi(x,y,black,true);
        var al = document.getElementById('alert');
        al.innerHTML=`${black?"黑方":"白方"}方获胜`;
    });

});
window.onerror=function (e) {
        alert(111)
}

var ccc =G.pointSingle.filter(function (item) {
    return item.fangAns.some(aa=>aa.points.every(bb=>bb!=item));
});